package com.service.web;

import java.io.Serializable;
import java.util.List;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import com.service.module.Module;
import com.service.module.ModuleRN;
import com.service.user.User;
import com.service.user.UserRN;
import com.service.util.FunctionUtil;

@ManagedBean(name = "contextoBean")
@SessionScoped
public class ContextoBean implements Serializable {
	
	private static final long serialVersionUID = -7338748629040363408L;
	
	private FunctionUtil fu = new FunctionUtil();
	private User usuarioLogado = null;
	private List<Module> listModules;
	private int count = 1800;
	private String timer = "00:30:00";

	public User getUsuarioLogado() {
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext external = context.getExternalContext();
		String login = external.getRemoteUser();
		if (this.usuarioLogado == null
				|| !login.equals(this.usuarioLogado.getLogin())) {
			if (login != null) {
				UserRN usuarioRN = new UserRN();
				this.usuarioLogado = usuarioRN.buscaPorLogin(login);
			}
		}
		return usuarioLogado;
	}

	public List<Module> getListModules() throws Throwable {
		Integer userID = this.getUsuarioLogado().getUserID();
		ModuleRN moduleRN = new ModuleRN();
		listModules = moduleRN.listModule(userID);
		return listModules;
	}
	
	public void resetTimer() {
		setCount(1800);
		setTimer("00:30:00");
	}

	public void decrement() {
		setCount(getCount() - 1);
		setTimer(fu.getDurationString(getCount()));
	}

	public void setUsuarioLogado(User usuarioLogado) {
		this.usuarioLogado = usuarioLogado;
	}

	public void setListModules(List<Module> listModules) {
		this.listModules = listModules;
	}
	
	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public String getTimer() {
		return timer;
	}

	public void setTimer(String timer) {
		this.timer = timer;
	}
}
